<script lang="ts" setup>
import type { SystemCustomerApi } from '#/api/system/customer';

import { computed, watchEffect } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { createCustomer, updateCustomer } from '#/api/system/customer';

import { useFormSchema } from '../data';

interface Props {
  customerData?: null | SystemCustomerApi.SystemCustomer;
}

const props = withDefaults(defineProps<Props>(), {
  customerData: null,
});

const [Drawer, drawerApi] = useVbenDrawer({
  title: computed(() => (props.customerData ? '编辑客户' : '新增客户')),
});

const [Form, formApi] = useVbenForm({
  schema: useFormSchema(),
  submitButtonOptions: {
    text: computed(() => (props.customerData ? '更新' : '创建')),
  },
});

const drawerTitle = computed(() => (props.customerData ? '编辑客户' : '新增客户'));

watchEffect(() => {
  if (props.customerData) {
    formApi.setValues(props.customerData);
  } else {
    formApi.resetForm();
  }
});

async function handleSubmit(values: Record<string, any>) {
  try {
    if (props.customerData) {
      await updateCustomer(props.customerData.id, values);
    } else {
      await createCustomer(values);
    }
    drawerApi.close();
  } catch (error) {
    console.error('提交失败:', error);
  }
}

defineExpose({
  drawerTitle,
});
</script>

<template>
  <Drawer>
    <Form @submit="handleSubmit" />
  </Drawer>
</template>